package cn.kimoon.dau_android;

import android.annotation.SuppressLint;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.kaopiz.kprogresshud.KProgressHUD;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

import cn.kimoon.dau_android.API.ApiDAU;
import cn.kimoon.dau_android.API.AppClient;
import cn.kimoon.dau_android.Model.ModelCollectorInfo;
import cn.kimoon.dau_android.Model.ModelContactItem;
import cn.kimoon.dau_android.Model.ModelLogin;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by xiangdong on 2016/11/23.
 */

public class HumitureFragment extends Fragment implements View.OnClickListener {
    private View headerView;
    private Button headerLowerBtn;
    private Button headerUpperBtn;
    private ListView listView;

    private OptionsPickerView pickerView;
    private ArrayList<Integer> option1Items;
    private ArrayList<ArrayList<Integer>> option2Items;

    private ModelCollectorInfo info;                   // 模型
    private HumitureAdapter adapter;                   // 适配器

    public final int kMinValue = -50;                  // 温度的下限
    public final int kMaxValue = 100;                  // 温度的上限

    public void setInfo(ModelCollectorInfo info) {
        this.info = info;

        refreshWholeView();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_humiture, container, false);
        initLogicData();
        initSubViews(inflater, view);
        return view;
    }

    private void initLogicData() {
        option1Items = new ArrayList<>();
        for (int i = 0; i < kMaxValue - kMinValue + 1; i++) {
            option1Items.add(i + kMinValue);
        }

        option2Items = new ArrayList<>();
        option2Items.add(option1Items);
    }

    private void initSubViews(LayoutInflater inflater, View view) {
        headerView = inflater.inflate(R.layout.list_humiture_header, null, false);
        headerLowerBtn = (Button) headerView.findViewById(R.id.humiture_temp_lower_btn);
        headerUpperBtn = (Button) headerView.findViewById(R.id.humiture_temp_upper_btn);
        headerLowerBtn.setOnClickListener(this);
        headerUpperBtn.setOnClickListener(this);

        listView = (ListView) view.findViewById(R.id.humiture_list_view);
        listView.addHeaderView(headerView);
        adapter = new HumitureAdapter(info, getActivity());
        listView.setAdapter(adapter);
    }

    private void refreshWholeView() {
        if (info != null && headerLowerBtn != null && headerUpperBtn != null) {
            System.out.println("打印" + info + "---" + headerLowerBtn);
            headerLowerBtn.setText(String.format("%.0f℃", info.temperature_secure_line_lower / 10.0));
            headerUpperBtn.setText(String.format("%.0f℃", info.temperature_secure_line_upper / 10.0));
        }

        if (adapter != null){
            adapter.setData(info);
        }
    }

    // 按键处理
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.humiture_temp_lower_btn:
            case R.id.humiture_temp_upper_btn:
                tempSecureLineBtnTapped();
                break;
        }
    }

    private void tempSecureLineBtnTapped() {
        if (info == null) {
            return;
        }

        if (pickerView == null) {
            pickerView = new OptionsPickerView(getActivity());
            pickerView.setPicker(option1Items, option2Items, false);
            pickerView.setLabels("℃", "℃");
            pickerView.setCyclic(false, false, false);

            pickerView.setSelectOptions(
                    (int)(info.temperature_secure_line_lower / 10.0) - kMinValue,
                    (int)(info.temperature_secure_line_upper / 10.0)- kMinValue);        // 指定滚动的位置
        }
        pickerView.show();
        pickerView.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                int lower = option1Items.get(options1);
                int upper = option2Items.get(0).get(option2);
                int min = (lower < upper) ? lower : upper;
                int max = (upper > lower) ? upper : lower;
                requestSetSecureLine(min * 10, max * 10);
            }
        });
    }

    // 网络请求
    private void requestSetSecureLine(final int lower, final int upper) {
        if (lower == info.temperature_secure_line_lower && upper == info.temperature_secure_line_upper) {
            return;
        }

        final KProgressHUD hud = KProgressHUD.create(getActivity(), KProgressHUD.Style.SPIN_INDETERMINATE).show();

        Map<String, String> parameters = new HashMap<>();
        parameters.put("id", String.valueOf(info.id));
        parameters.put("temperature_secure_line_lower", String.valueOf(lower));
        parameters.put("temperature_secure_line_upper", String.valueOf(upper));

        ApiDAU apiDAU = AppClient.retrofit().create(ApiDAU.class);
        Call<ModelLogin> call = apiDAU.apiSecureLine(parameters);
        call.enqueue(new Callback<ModelLogin>() {
            @Override
            public void onResponse(Call<ModelLogin> call, Response<ModelLogin> response) {
                hud.dismiss();
                if (response.body() != null && response.body().errCode == 200) {
                    info.temperature_secure_line_lower = lower;
                    info.temperature_secure_line_upper = upper;
                    refreshWholeView();
                } else {
                    String msg = (response.body() == null ? response.message() : response.body().msg);
                    Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ModelLogin> call, Throwable t) {
                hud.dismiss();
                Toast.makeText(getActivity(), R.string.internet_request_failed, Toast.LENGTH_SHORT).show();
            }
        });
    }
}
